<template>
  <!--结算合同-->
  <div class="out-of-account">
    <div style="padding:10px;margin:10px;background:#fff">
      <el-select @change="projectChange" v-model="searchForm.proId" style="margin-right: 6px" filterable clearable placeholder="请选择项目" value-key="name">
        <el-option v-for="item in projects" :key="item.id" :label="item.projectName" :value="item.id" />
      </el-select>
      <el-input style="width:150px" v-model="searchForm.settle" type="text" placeholder="结算合同" clearable/>
      <el-input style="width:150px" v-model="searchForm.name" type="text" placeholder="设备名" clearable/>
      <el-date-picker
        style="margin-left: 8px"
        v-model="searchForm.time"
        unlink-panels
        value-format="timestamp"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
      >
      </el-date-picker>
      <el-button @click="toSearch" type="primary" icon="el-icon-search" size="small" style="margin: 4px 0 0 6px" >查询</el-button>
    </div>
    <div style="padding:10px;margin:10px;background:#fff">
      <div>
        <el-button @click="addDialog" icon="el-icon-plus" type="success" size="small">新增</el-button>
        <el-button :disabled="table.selectedRowKeys.length > 0?false:true" @click="deleteData" icon="el-icon-delete" type="danger" size="small">删除</el-button>
        <a-table
          bordered
          :data-source="table.data"
          size="middle"
          :rowKey="record => record.itemId"
          :loading="table.loading"
          :pagination="table.pagination"
          :scroll="table.data.length > 0 ?{ x: 400}:{}"
          style="margin-top: 1em"
          :customRow="rowClick"
          :row-selection="{ selectedRowKeys: table.selectedRowKeys, onChange: selectionChange, selections: [{
            key: 'all-data',
            text: '全选',
            onSelect: () => {
              this.selectedRowKeys =  table.data.map(item =>{return item.itemId});
            }
          }]}"
        >
          <a-table-column align="center" key="settleNo" title="结算合同" data-index="settleNo" />
          <a-table-column align="center" key="item" title="设备名" data-index="item" />
          <a-table-column align="center" key="invoiceNo" title="发票编号" data-index="invoiceNo" />
          <a-table-column align="center" key="invoicePrice" title="发票金额" data-index="invoicePrice" />
          <a-table-column align="center" key="files" title="发票">
            <template slot-scope="text">
              <div v-for="(item, key) in text.files" :key="key">
                <el-image fit="contain" style="height: 40px; width:auto" :src="item.url" :preview-src-list="[item.name]" v-if="item!=null && item != ''">
                  <div slot="error" class="image-slot">
                    <i class="el-icon-picture-outline"></i>
                  </div>
                </el-image>
              </div>
            </template>
          </a-table-column>
          <a-table-column align="center" key="remark" title="备注" data-index="remark" />
          <a-table-column :width="100" align="center" key="createBy" title="创建人" data-index="createBy" />
          <a-table-column :width="100" align="center" key="createTime" title="创建时间" data-index="createTime">
            <template slot-scope="t">
              {{dateFormat(parseInt(t))}}
            </template>
          </a-table-column>
        </a-table>
      </div>
    </div>

    <!--模态框-->
    <el-dialog v-el-drag-dialog :title="title" :visible.sync="dialog.visible" width="1000px">
      <el-form :model="dialog.form" status-icon>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="结算合同" label-width="80px" size="small" prop="settleNo">
              <el-input v-model="dialog.form.settleNo"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="发票编号" label-width="80px" size="small" prop="invoiceNo">
              <el-input v-model="dialog.form.invoiceNo"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="发票金额" label-width="80px" size="small" prop="invoicePrice">
              <el-input v-model="dialog.form.invoicePrice"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" label-width="80px" size="small" prop="remark">
              <el-input v-model="dialog.form.remark" type="textarea"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <div class="clearfix">
              <a-upload
                :action="fileUploadUrl"
                list-type="picture-card"
                :file-list="fileList"
                @change="handleChange"
              >
                <div v-if="fileList.length < 8">
                  <a-icon type="plus" />
                  <div class="ant-upload-text">
                    Upload
                  </div>
                </div>
              </a-upload>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialog.visible = false">取 消</el-button>
        <el-button size="small" type="primary" @click="dialogCommit">确 定</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
  import "@/styles/auto-style.css";
  import { getAction, postActionByJson, postActionByQueryString } from "@/api/manage";
  import { dateFormat } from "@/utils/format";
  import { beforeUpload, uploadStatusChange } from '@/utils/upload'
  import elDragDialog from "@/directive/el-drag-dialog";

  export default {
    directives: { elDragDialog },

    watch: {
      
    },
    created() {
      this.loadProjects()
    },
    mounted() {
      var that = this;
      // <!--把window.onresize事件挂在到mounted函数上-->
      window.onresize = () => {
        return (() => {
          that.windowHeight = document.documentElement.clientHeight  - 130; // 高
        })()
      };
    },
    data() {
      const fileUploadUrl = process.env.VUE_APP_BASE_API + 'file/uploadCache'

      return {
        projects: [],
        fileList: [],
        fileUploadUrl,
        title: '',
        table: {
          selectedRowKeys: [],
          loading: false,
          data: [],
          pagination: {
            showQuickJumper: true,
            showSizeChanger: true,
            pageSizeOptions: ['15', '30', '35'],
            current: 1,
            pageSize: 15,
            total: 0,
            onChange: (item) => {
              this.table.pagination.current = item
              this.toSearch()
            },
            onShowSizeChange: (current, pageSize) => {
              this.table.pagination.pageSize = pageSize
              this.toSearch()
            }, // 改变每页数量时更新显示
          },
        },
        options: {
          contracts: [],
          projects: []
        },
        dialog: {
          form: {
            //redis中的图片id
            images: []
          },
          visible: false
        },
        purchaseProjects: [],
        searchForm: {},
        windowHeight: document.documentElement.clientHeight - 130, // 页面高度
        margin: 0, // left-sider 移动距离
        url: {
          findSettlement: '/contract/settle/findSettlement',
          saveOrUpdateSettle: '/contract/settle/saveOrUpdateSettle',
          findByAll: '/purchase/project/findAllLike'
        }
      }
    },
    methods: {
      rowClick(row, index) {
        return {
          on: {
            click: () => {
              let index = this.table.selectedRowKeys.indexOf(row.itemId)
              if(index === -1){
                this.table.selectedRowKeys.push(row.itemId)
              }else{
                this.table.selectedRowKeys.splice(index, 1)
              }
            }
          }
        }
      },
      loadProjects() {
        getAction(this.url.findByAll)
        .then(response => {
          this.projects = response.data
        }).catch((e)=>{

        }).finally(()=>{})
      },
      projectChange(){

      },
      handleChange({ fileList }){
        this.fileList = fileList;
      },
      selectionChange(ids, rows){
        const selectedId = []
        ids.map(item => {
          selectedId.push(item)
        })
        this.table.selectedRowKeys = selectedId
      },
      addDialog(){
        this.title = '新增结算合同'
        this.dialog.form = {}
        this.dialog.visible = true
      },
      updateDialog(record){
        this.title = '修改入账信息'
        this.dialog.form = record
        this.dialog.visible = true
      },
      dialogCommit(){
        //获取上传的图片redis id
        let arr =[]
        this.fileList.map(i=>{
          if(i.response.status === 200){
            arr.push(i.response.fileId)
          }
        })
        this.dialog.form.images = arr
        //绑定勾选项id
        this.dialog.form.ids = this.table.selectedRowKeys
        postActionByJson(this.url.saveOrUpdateSettle, this.dialog.form)
        .then(resp =>{
          this.$message.success(resp.message)
        }).catch(()=>{
          this.$message.error('提交失败')
        }).finally(()=>{
          this.dialog.visible = false
          this.table.selectedRowKeys = []
          this.toSearch()
        })
      },
      deleteData(){
        this.$confirm('确认删除改条信息吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          postActionByQueryString(this.url.delete, {ids: this.table.selectedRowKeys})
          .then(resp =>{
            this.$message.success(resp.message)
          }).catch(()=>{
            this.$message.error('删除失败')
          }).finally(()=>{
            this.toSearch()
          })
        })
      },
      toSearch() {
        this.table.loading = true
     /*   let form = Object.assign({}, this.searchForm)*/
        // if(this.searchForm.time && this.searchForm.time.length > 0){
        //   this.searchForm.startTime = this.searchForm.time[0]
        //   this.searchForm.endTime = this.searchForm.time[1]
        // }
        // this.$delete(searchForm,'time')
        getAction(this.url.findSettlement, {
          contractNo: this.searchForm.contractNo,
          item: this.searchForm.item,
          proId: this.searchForm.proId,
          pageNum: this.table.pagination.current,
          pageSize: this.table.pagination.pageSize
        })
        .then(resp =>{
          if (resp.data){
            this.table.data = resp.data.records
            this.table.pagination.current = parseInt(resp.data.current)
            this.table.pagination.pageSize = parseInt(resp.data.size)
            this.table.pagination.total = parseInt(resp.data.total)
          }
        }).catch(()=>{
          this.$message.error('查询失败')
        }).finally(()=>{
          this.table.loading = false
        })
      },
      /**
       * left-sider 收缩事件
       */
      changeMargin(){
        this.margin = this.margin == 0?-460-14:0
      },
      /**
       * 加载下拉框所有项目
       */
      loadPurchaseProjects() {
        getAction(this.url.findAllLike)
        .then((resp) => {
          this.options.projects = resp.data
        }).catch(()=>{
          this.$message.error('项目加载失败')
        })
      },
      loadContracts(){
        getAction(this.url.findSaleContractAll, { projectId: this.searchForm.projectId })
        .then(resp => {
          this.options.contracts = resp.data
        }).catch(()=>{
          this.$message.error('销售合同加载失败')
        })
      },
      proSelectChange() {
        this.loadContracts();
      },
      dateFormat,
      beforeUpload,
      uploadStatusChange
    }
  }
</script>

<style lang="scss" scoped>
  .out-of-account {

    .left-layout{
      margin-top: 1em;
      margin-right: 1em;
    }
    /deep/.el-divider--horizontal {
      marign: 8px 0!important;
    }
    /deep/.el-form-item__content{
      height:auto;
      line-height:32px;
      margin-left:90px!important
    }
    .left-container {
      background: #fff;
      position: relative;
      .sider-btn {
        cursor: pointer;top:18px;position: absolute;font-size: 28px;color:#73767b;
      }
      .el-icon-s-fold {
        right: 0px;
      }
      .el-icon-s-unfold {
        top: -6px;
        right: -57px;
        border: 1px dashed #d5d5d5;
        background: #fff;
      }
      .attr-row {
        .el-col {
          text-align: center;
          span {
            cursor: pointer;
          }
        }
      }
    }

  }
  /deep/.el-picker-panel {
    z-index: 2900!important
  }
</style>
